package com.alennus.blog.controller;

import com.alennus.blog.domain.Menu;
import com.alennus.blog.domain.RoleMenu;
import com.alennus.blog.response.WebApiResponse;
import com.alennus.blog.service.MenuService;
import com.alennus.blog.service.RoleMenuService;
import com.alennus.blog.utils.DateUtils;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by pactera on 2018/5/18.
 */
@RestController
@RequestMapping("/menu")
public class MenuController {



    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleMenuService roleMenuService;


    @PostMapping("/save")
    public WebApiResponse<Menu> save(@Valid Menu menu){
        if(StringUtils.isEmpty(menu.getParentId())){
            menu.setParentId("-1");
        }
        if(StringUtils.isEmpty(menu.getId())){
            menu.setCreatedDate(DateUtils.getCurrentDatetime());
            menu.setUpdateDate(DateUtils.getCurrentDatetime());
        }else{
            menu.setUpdateDate(DateUtils.getCurrentDatetime());
        }
        return WebApiResponse.success(menuService.save(menu));
    }

    @GetMapping("/{parentId}")
    public WebApiResponse<Page<Menu>> menu(@PathVariable("parentId") String parentId, Pageable pageable){
        Menu menu = new Menu();
        if(!parentId.equals("0")){
            menu.setParentId(parentId);
        }
        return WebApiResponse.success(menuService.findMenu(menu,pageable));
    }

    @GetMapping("/tree")
    public WebApiResponse<List<Menu>> menuTree(){

        return WebApiResponse.success(menuService.getMenuTree());
    }

    @GetMapping("/trees/{roleId}")
    public WebApiResponse<List<Menu>> menuTrees(@PathVariable String roleId){
        List<String> checkedMenu =  Lists.newArrayList();
        if(!StringUtils.isEmpty(roleId)){
            List<RoleMenu> roleMenus = roleMenuService.findByRoleId(roleId);
            for(RoleMenu roleMenu : roleMenus){
                checkedMenu.add(roleMenu.getMenuId());
            }
        }
        return WebApiResponse.success(menuService.menuTree("-1",checkedMenu));
    }
    @PostMapping("/delete")
    public WebApiResponse<Menu> delete(@RequestBody List<Menu> menus){
        menuService.deleteAll(menus);
        return WebApiResponse.success();
    }


}
